package cn.hbu.zlfw.research.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hbu.zlfw.admin.entity.Expert;
import cn.hbu.zlfw.admin.entity.RootAdmin;
import cn.hbu.zlfw.admin.entity.ScienceExpert;
import cn.hbu.zlfw.admin.entity.UnitAdmin;
import cn.hbu.zlfw.admin.service.ExpertService;
import cn.hbu.zlfw.annotation.OperatorLog;
import cn.hbu.zlfw.annotation.OperatorType;
import cn.hbu.zlfw.common.base.service.BaseService;
import cn.hbu.zlfw.common.util.SessionUtil;
import cn.hbu.zlfw.common.util.ShortMessageUtil;
import cn.hbu.zlfw.common.util.Utility;
import cn.hbu.zlfw.dic.entity.DicUserType;
import cn.hbu.zlfw.dic.service.DicSchoolService;
import cn.hbu.zlfw.dic.service.DicUserTypeService;
import cn.hbu.zlfw.job.entity.ShortMessage;
import cn.hbu.zlfw.job.service.ShortMessageService;
import cn.hbu.zlfw.research.entity.Researcher;
import cn.hbu.zlfw.research.service.ResearcherService;

/**
 * 
 * @ClassName: ResearcherController 
 * @Description: 科研人员控制层
 * @author 王鹏伟<1223443289@qq.com>
 * @date 2017年10月23日 下午5:59:33  
 * @version V1.0
 */
@Controller("researcherController")
@RequestMapping("/researcher")
public class ResearcherController {
	/**
	 * 日志
	 */
	public final Logger logger=LoggerFactory.getLogger(Researcher.class);
	
	/**
	 * 注入HttpServletRequest
	 */
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private DicSchoolService dicSchoolService;
	/**
	 * 注入Service
	 */
	@Autowired
	private ResearcherService researcherService;
	
	@Autowired
	private ShortMessageService shortMessageService;
	
	@Autowired
	private BaseService baseService;
	
	@Autowired
	private DicUserTypeService dicUserTypeService;
	
	@Autowired
	private ExpertService expertService;
	/**
	 * 
	 * @Title: login 
	 * @Description: 用户登录操作
	 * @param researcher
	 * @return String   
	 * @throws
	 */
	@ResponseBody
	@OperatorLog(type=OperatorType.OTHER,description="科研人员成功登录！")
	@RequestMapping("/login.html")
	public String login(@ModelAttribute("researcher") Researcher researcher) {
		Researcher user=this.researcherService.
				findResearcherTologin(researcher.getPhoneNumber(),researcher.getPassword());
		if(user==null) {	//密码不匹配登录失败
			return "fail";
		} else {			//登录成功进行页面跳转
			this.request.getSession().setAttribute(SessionUtil.SESSION_USER_KEY, user);
			return "success";
		}
	}
	/**
	 * 
	 * @Title: regist 
	 * @Description: 用户注册
	 * @param researcher
	 * @return String   
	 * @throws
	 */
	@ResponseBody
	@OperatorLog(type=OperatorType.SAVE,description="科研人员成功注册！")
	@RequestMapping("/regist.html")
	public String regist(@ModelAttribute("researcher") Researcher researcher,
			@RequestParam(value="code",required=false) int code) {
		//查询注册短信
		ShortMessage shortMessage=this.shortMessageService
				.findShortMessageByParams(researcher.getPhoneNumber(), ShortMessage.REGISTER);
		if(shortMessage==null) {	//短信已过期被删除
			return "past";
		}
		if(shortMessage.getCode()==code) {
			//存储科研人员信息
			researcher.setDelState(0);
			researcher.setCreateTime(new Date());
			researcher.setUpdateTime(new Date());
			researcher.setUserType(DicUserType.RESEARCHER_USER);
			researcherService.save(researcher);
			return "success";
		} else {			//验证码
			return "fail";
		}
		
	}
	@OperatorLog(type=OperatorType.OTHER,description="进行注册")
	@RequestMapping("/toRegist.html")
	public String toRegist(ModelMap map) {
		map.put("dicSchools", this.dicSchoolService.findAll());
		return "regist/regist";
	}
	/**
	 * 
	 * @Title: sendRegistCode 
	 * @Description: 发送注册验证码
	 * @param phoneNumber
	 * @return String   
	 * @throws
	 */
	@ResponseBody
	@OperatorLog(type=OperatorType.UPDATE,description="发送注册验证码")
	@RequestMapping("/sendRegistCode.html")
	public String sendRegistCode(@RequestParam("phoneNumber") String phoneNumber) {
		//判断手机号是否已经被注册过
		Researcher user=this.researcherService.findResearcherByPhone(phoneNumber);
		if(user==null) {  //手机号没有被注册过，
			//存储短信信息
			Integer code=ShortMessageUtil.sendShortMessageCode(phoneNumber);
			ShortMessage shortMessage=new ShortMessage();
			shortMessage.setDelState(0);
			shortMessage.setCode(code);
			shortMessage.setPhoneNumber(phoneNumber);
			shortMessage.setType(shortMessage.REGISTER);
			shortMessage.setUserType(DicUserType.RESEARCHER_USER);	
			shortMessage.setCreateTime(new Date());
			//判断该手机号是否已经有同类型短信：保持一个用户最多只有个同类型短信
			ShortMessage tempshortMessage=
					this.shortMessageService.findShortMessageByParams(phoneNumber,ShortMessage.REGISTER);
			if(tempshortMessage==null) {	//没有同类型短信
				this.shortMessageService.save(shortMessage);
			}else {	//有同类型短信:删除原来的短信，再保存
				this.shortMessageService.delete(tempshortMessage);
				this.shortMessageService.save(shortMessage);
			}
			return code.toString();
		}else {		//手机号已经被注册
			return "fail";
		}
	}
	/**
	 * 
	 * @Title: valid 
	 * @Description: 忘记密码-验证身份
	 * @return String   
	 * @throws
	 */
	@ResponseBody
	@OperatorLog(type=OperatorType.OTHER,description="科研人员忘记密码，验证身份")
	@RequestMapping("/findUser.html")
	public String findUser(@RequestParam("phoneNumber") String phoneNumber,@RequestParam("userType") int userType) {
		Object user = new Object();
		if(DicUserType.ROOT_ADMIN_USER.equals(userType)){
			user = new RootAdmin();
			try{
				user=(RootAdmin) this.researcherService.findByPhone(phoneNumber,user);
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		else if(DicUserType.SCIENCE_SERVICE_USER.equals(userType)){
			user = new ScienceExpert();
			user=(ScienceExpert) this.researcherService.findByPhone(phoneNumber,user);
		}
		else if(DicUserType.RESEARCHER_USER.equals(userType)){
			user = new Researcher();
			user=(Researcher) this.researcherService.findByPhone(phoneNumber,user);
		}
		else if(DicUserType.UNIT_ADMIN_USER.equals(userType)){
			user = new UnitAdmin();
			user=(UnitAdmin) this.researcherService.findByPhone(phoneNumber,user);
		}else if(DicUserType.EXPERT_SERVICE_USER.equals(userType)){
			user = new Expert();
			user=(Expert) this.researcherService.findByPhone(phoneNumber,user);
		}else{
			user = null;
		}
		if(user!=null) 
			return "success";
		else
			return "fail";
	}
	/**
	 * 
	 * @Title: valid 
	 * @Description: 忘记密码-验证身份
	 * @return String   
	 * @throws
	 */
	@ResponseBody
	@OperatorLog(type=OperatorType.OTHER,description="科研人员忘记密码，验证身份")
	@RequestMapping("/valid.html")
	public String valid(@RequestParam("phoneNumber") String phoneNumber,@RequestParam("userType") int userType) {
		//判断手机号是否已经被注册过
		String flag = findUser(phoneNumber,userType);
		if("success".equals(flag)) {  //手机号已经被注册-发送忘记密码短信
			//存储短信信息
			Integer code=ShortMessageUtil.sendShortMessageCode(phoneNumber);
			ShortMessage shortMessage=new ShortMessage();
			shortMessage.setCode(code);
			shortMessage.setPhoneNumber(phoneNumber);
			shortMessage.setType(shortMessage.FORGET_PASSWORD);
			shortMessage.setUserType(DicUserType.RESEARCHER_USER);	
			shortMessage.setDelState(0);
			shortMessage.setCreateTime(new Date());
			//判断该手机号是否已经有同类型短信：保持一个用户最多只有个同类型短信
			ShortMessage tempshortMessage=
					this.shortMessageService.findShortMessageByParams(phoneNumber,ShortMessage.FORGET_PASSWORD);
			if(tempshortMessage==null) {	//没有同类型短信
				this.shortMessageService.save(shortMessage);
			}else {	//有同类型短信:删除原来的短信，再保存
				this.shortMessageService.delete(tempshortMessage);
				this.shortMessageService.save(shortMessage);
			}
			return code.toString();
		}else {		      //手机号没有被注册
			return "fail";
		}
	}
	/**
	 * 
	 * @Title: setPassword 
	 * @Description: 忘记密码-设置新密码
	 * @return String   
	 * @throws
	 */
	@ResponseBody
	@OperatorLog(type=OperatorType.OTHER,description="用户修改密码")
	@RequestMapping("/set.html")
	public String set(@RequestParam("password") String password,@RequestParam("phoneNumber") String phoneNumber,
			@RequestParam("code") int code,@RequestParam("userType") int userType) {
		//查询修改密码短信
		ShortMessage shortMessage=this.shortMessageService
				.findShortMessageByParams(phoneNumber, ShortMessage.FORGET_PASSWORD);
		if ( shortMessage == null ) {	//短信已过期被删除
			return "past";
		}
		if(shortMessage.getCode() == code) {
			if(DicUserType.ROOT_ADMIN_USER.equals(userType)){
				RootAdmin user = new RootAdmin();
				try{
					user=(RootAdmin) this.researcherService.findByPhone(phoneNumber,user);
					user.setPassword(password);
					baseService.update(user);
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			else if(DicUserType.SCIENCE_SERVICE_USER.equals(userType)){
				ScienceExpert user = new ScienceExpert();
				user=(ScienceExpert) this.researcherService.findByPhone(phoneNumber,user);
				user.setPassword(password);
				baseService.update(user);
			}
			else if(DicUserType.RESEARCHER_USER.equals(userType)){
				Researcher user = new Researcher();
				user=(Researcher) this.researcherService.findByPhone(phoneNumber,user);
				user.setPassword(password);
				baseService.update(user);
			}
			else if(DicUserType.UNIT_ADMIN_USER.equals(userType)){
				UnitAdmin user = new UnitAdmin();
				user=(UnitAdmin) this.researcherService.findByPhone(phoneNumber,user);
				user.setPassword(password);
				this.baseService.update(user);
			}

			return "success";
		} else {	//验证码输入错误
			return "fail";
		}
	}
	
	@OperatorLog(type=OperatorType.OTHER,description="修改密码")
	@RequestMapping("/toupdate.html")
	public String toupdate(ModelMap map) {
		Object user = SessionUtil.getLoginUser(request);
		map.put("phoneNumber", Utility.getPropertyCollectByReflect(user, "phoneNumber"));
		return "admin/researcher/updateresearcher";
	}
}
